package com.haohan.cloud.scm.opc.core.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.haohan.cloud.scm.api.constant.enums.opc.AllocateTypeEnum;
import com.haohan.cloud.scm.api.constant.enums.opc.SummaryStatusEnum;
import com.haohan.cloud.scm.api.constant.enums.saleb.BuyOrderStatusEnum;
import com.haohan.cloud.scm.api.constant.enums.saleb.DetailSummaryFlagEnum;
import com.haohan.cloud.scm.api.goods.dto.GoodsModelDTO;
import com.haohan.cloud.scm.api.opc.entity.SummaryOrder;
import com.haohan.cloud.scm.api.opc.req.CreatePurchaseOrderWithSummaryReq;
import com.haohan.cloud.scm.api.opc.req.CreateSummaryOrderReq;
import com.haohan.cloud.scm.api.opc.req.OpcSummaryOrderListReq;
import com.haohan.cloud.scm.api.opc.resp.TemporarySummaryOrderResp;
import com.haohan.cloud.scm.api.opc.trans.OpcTrans;
import com.haohan.cloud.scm.api.product.entity.ProductInfo;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseOrder;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseOrderDetail;
import com.haohan.cloud.scm.api.purchase.req.AddPurchaseOrderReq;
import com.haohan.cloud.scm.api.purchase.resp.PurchaseOrderResp;
import com.haohan.cloud.scm.api.saleb.dto.BuyOrderDetailDTO;
import com.haohan.cloud.scm.api.saleb.feign.SalebFeignService;
import com.haohan.cloud.scm.api.saleb.req.SalebSummaryGoodsNumReq;
import com.haohan.cloud.scm.common.tools.exception.EmptyDataException;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.opc.core.IScmOpcDemandSummaryService;
import com.haohan.cloud.scm.opc.core.IScmOpcOperationService;
import com.haohan.cloud.scm.opc.service.SummaryOrderService;
import com.haohan.cloud.scm.opc.utils.ScmOpcUtils;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * @author cx
 * @date 2019/5/29
 */
@Service
@AllArgsConstructor
@Slf4j
public class ScmOpcDemandSummaryServiceImpl implements IScmOpcDemandSummaryService {

    private final SalebFeignService salebFeignService;

    private final SummaryOrderService summaryOrderService;

    private final IScmOpcOperationService iScmOpcOperationService;

    private final ScmOpcUtils scmOpcUtils;

    /**
     * 查询客户下单、汇总商品数量
     *
     * @param req
     * @return
     */
    @Override
    public List<BuyOrderDetailDTO> queryDemandSummaryList(SalebSummaryGoodsNumReq req) {
        //设置查询状态
        req.setSummaryFlag(DetailSummaryFlagEnum.wait.getType());
        req.setStatus(BuyOrderStatusEnum.wait.getType());
        //查询汇总列表
        R result = salebFeignService.summaryGoodsNumList(req, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(result)) {
            throw new ErrorDataException("查询汇总列表失败");
        }
        List<BuyOrderDetailDTO> list = new ArrayList<>();
        List respList = (List) result.getData();
        for (int i = 0; i < respList.size(); i++) {
            BuyOrderDetailDTO detail = BeanUtil.toBean(respList.get(i), BuyOrderDetailDTO.class);
            list.add(detail);
        }
        return list;
    }

    /**
     * 返回汇总单和汇总临时数据列表
     *
     * @param req
     * @return
     */
    @Override
    public List<TemporarySummaryOrderResp> getSummaryOrderList(OpcSummaryOrderListReq req) {
        String pmId = req.getPmId();
        List<TemporarySummaryOrderResp> orderList = new ArrayList<>();
        //查询当前租户待处理汇总单(未生成采购单的汇总单)
        SummaryOrder queryOrder = new SummaryOrder();
        BeanUtil.copyProperties(req,queryOrder);
        queryOrder.setSummaryStatus(SummaryStatusEnum.wait);
        List<SummaryOrder> orders = summaryOrderService.list(Wrappers.query(queryOrder));
        //若存在未生成采购单的汇总单，查询库存
        if(CollUtil.isNotEmpty(orders)){
            for(SummaryOrder order : orders){
                TemporarySummaryOrderResp resp = new TemporarySummaryOrderResp();
                BeanUtil.copyProperties(order,resp);
                // 库存
                ProductInfo productInfo = scmOpcUtils.queryGoodsStorage(pmId, order.getGoodsModelId());
                resp.setGoodsStorage(productInfo.getProductNumber());
                // TODO 损耗率
                resp.setLossRate(BigDecimal.ZERO);
                // 订单数
                resp.setOrderNum(null != order.getBuyerNum() ? order.getBuyerNum() : 1);
                orderList.add(resp);
            }
        }
        //查询未汇总采购商品数量
        SalebSummaryGoodsNumReq goodsNumReq = new SalebSummaryGoodsNumReq();
        BeanUtil.copyProperties(req,goodsNumReq);
        List<BuyOrderDetailDTO> list = this.queryDemandSummaryList(goodsNumReq);
        if (CollUtil.isEmpty(list) && CollUtil.isEmpty(orders)) {
            throw new EmptyDataException("没有需采购数据");
        }
        //临时数据goods下查询库存并转换

        for (BuyOrderDetailDTO detail : list) {
            //将返回数据添加到返回列表
            String goodsModelId = detail.getGoodsModelId();
            GoodsModelDTO model = scmOpcUtils.fetchGoodsModel(goodsModelId);
            //数据转换
            TemporarySummaryOrderResp result = OpcTrans.temporarySummaryOrder(model, detail);
            result.setPmId(pmId);
            // 库存
            ProductInfo productInfo = scmOpcUtils.queryGoodsStorage(pmId, goodsModelId);
            result.setGoodsStorage(productInfo.getProductNumber());
            // TODO 损耗率
            result.setLossRate(BigDecimal.ZERO);
            // TODO 订单数
            result.setOrderNum(1);
            orderList.add(result);
        }
        return orderList;
    }

    /**
     * 保存汇总单
     * @param resp
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SummaryOrder> createSummaryOrderForOrder(List<TemporarySummaryOrderResp> resp) {
        List<SummaryOrder> orders = new ArrayList<>();
        for(TemporarySummaryOrderResp r : resp){
            SummaryOrder queryOrder = new SummaryOrder();
            BeanUtil.copyProperties(r,queryOrder);
            queryOrder.setAllocateType(AllocateTypeEnum.purchase);
            if(StrUtil.isEmpty(queryOrder.getSummaryOrderId())){
                SummaryOrder order = iScmOpcOperationService.createSummaryByGoodsNeeds(queryOrder);
                orders.add(order);
            }
        }
        return orders;
    }

    /**
     * 创建汇总单 并生成采购单
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PurchaseOrderResp createPurchaseOrderWithSummaryOrder(CreatePurchaseOrderWithSummaryReq req) {
        String pmId = req.getPmId();
        // 创建汇总单
        // 已创建的汇总单
        List<SummaryOrder> useSummaryList = new ArrayList<>();
        List<PurchaseOrderDetail> purchaseOrderDetailList = new ArrayList<>();
        List<String> detailSnList = new ArrayList<>();
        for(CreateSummaryOrderReq summaryReq: req.getSummaryList()){
            summaryReq.setPmId(pmId);
            // 已创建采购单 状态修改
            summaryReq.setSummaryStatus(SummaryStatusEnum.purchase);
            try {
                SummaryOrder order = iScmOpcOperationService.createSummaryByGoodsNeeds(summaryReq.transTo());
                useSummaryList.add(order);
                // 生成采购明细
                PurchaseOrderDetail purchaseOrderDetail = scmOpcUtils.addPurchaseOrderDetail(order);
                purchaseOrderDetailList.add(purchaseOrderDetail);
                detailSnList.add(purchaseOrderDetail.getPurchaseDetailSn());
            }catch (Exception e){
                log.debug("==汇总单创建失败====" ,e.getMessage());
            }
        }
        if(CollUtil.isEmpty(purchaseOrderDetailList)){
            throw new ErrorDataException("创建采购单明细失败,无明细列表");
        }
        // 生成采购单
        AddPurchaseOrderReq addPurchaseOrderReq = new AddPurchaseOrderReq();
        addPurchaseOrderReq.setPmId(req.getPmId());
        addPurchaseOrderReq.setPurchaseDetailSn(detailSnList);
        PurchaseOrder purchaseOrder = scmOpcUtils.addPurchaseOrder(addPurchaseOrderReq);
        PurchaseOrderResp result = new PurchaseOrderResp();
        BeanUtil.copyProperties(purchaseOrder, result);
        result.setDetailList(purchaseOrderDetailList);
        return result;
    }

}
